<template>
  <div>
    <el-card v-loading="loading">

      <avue-crud :data="data" :option="option" @refresh-change="refreshChange" @row-save="rowSave" @row-update="rowUpdate"
        @row-del="rowDel" v-model:page="page" @size-change="sizeChange" @current-change="currentChange"></avue-crud>
    </el-card>

  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addXfactoryController, deleteXfactoryController, updateXfactoryController, getXfactoryController } from '@/api/firm.ts'
import { useUserStore } from '@/store/modules/user'

const { userMessage } = useUserStore()

const loading = ref(true)
const data = ref([]);


const page = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
})


const getData = () => {
  loading.value = true

  let Q = {
    index: page.value.currentPage,
    size: page.value.pageSize,
  }


  getXfactoryController(Q).then(res => {
    data.value = res.result
    page.value.total = res.page.total
    loading.value = false
  })
}


getData()

const option = ref({
  addBtn: userMessage.qx == 0,
  delBtn: userMessage.qx == 0,
  column: [
    { label: '名称', prop: 'name', rules: [{ required: true, message: '请输入名称', trigger: 'blur' }] },
    {
      label: '是否有效',
      prop: 'yx',
      type: 'switch',
      dicData: [

        { label: '无效', value: 0 },
        { label: '有效', value: 1 },
      ],
      value: 0
    }

  ]
});



const refreshChange = () => {
  getData()
};

const rowSave = (form, done, loading) => {
  // loading();
  addXfactoryController(form).then(res => {
    if (res !== 'error') {
      done(form);
      getData();
    } else {
      done();
    }
  })

};

const rowDel = (form, index, done) => {
  ElMessageBox.confirm('是否删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteXfactoryController(form.id).then(res => {
      ElMessage.success('删除成功!');
      done(form);

    })

  }).catch(() => { });
};

const rowUpdate = (form, index, done, loading) => {

  updateXfactoryController(form).then(res => {
    ElMessage.success('修改成功');
    done(form);
    if (form.id == userMessage.id) {
      Object.keys(userMessage).forEach(key => {
        userMessage[key] = form[key]
      });
    }
  })
};



function sizeChange(val) {
  page.value.currentPage = 1;
  page.value.pageSize = val;
  getData();
}

function currentChange(val) {
  page.value.currentPage = val;
  getData();
}
</script>